import { Injectable, NotFoundException } from '@nestjs/common';
import { CreateUserDto } from './dto/create-User.dto';
import { UpdateUserDto } from './dto/update-User.dto';
import { PrismaService } from 'src/prisma/prisma.service';

@Injectable()
export class UserService {
  constructor(private readonly prismaService: PrismaService) { }
  async create(createUserDto: CreateUserDto) {
    const res = await this.prismaService.sysUser.findFirst({
      where: {
        username: createUserDto.username
      }
    })
    console.log(res)
    if (res) {
      return '当前用户名已经存在'
    }
    console.log(createUserDto, "createUserDto")

    // await this.prismaService.$queryRaw`
    // INSERT INTO User (username, password)
    // VALUES (${createUserDto.username},${createUserDto.password});
    // `;

    // const newUser = await this.prismaService.sysUser.create({
    //   data: { ...createUserDto },
    // });
    return '插入数据成功'
  }

  async findAll() {
    // select 匹配字段
    return await this.prismaService.sysUser.findMany({
      skip: 1,
      take: 10,
      select: {
        username: true,
        id: true,
      },
    })
  }

  // 原生sql
  async findOne(id: number) {
    const result = await this.prismaService.$queryRaw`
      SELECT * FROM sysUser 
      WHERE id = ${id}
      `;
    return result
  }

  async update(id: number, updateUserDto: UpdateUserDto) {

    if (!id) {
      throw new NotFoundException(`不存在请求id`);
    }

    const reasult = await this.prismaService.sysUser.update({
      where: {
        id: id
      },
      data: {
        ...updateUserDto
      }
    })

    return '更新数据成功' + reasult
  }

  async remove(id: number) {
    const result = await this.prismaService.sysUser.deleteMany({
      where: { id }
    });

    if (result.count === 0) {
      throw new NotFoundException(`要删除的用户数据不存在`);
    }

    return { message: `User with ID ${id} deleted successfully` };
  }

  async findUserByUserName(username: string): Promise<any | undefined> {
    return this.prismaService.sysUser.findUnique({
      where: {
        username: username
      }
    })
  }

  async findUserById(id: string): Promise<any | undefined> {
    return this.prismaService.sysUser.findUnique({
      where: {
        id: parseInt(id, 10)
      }
    });
  }
}
